package model;

import javax.xml.bind.DataBindingException;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import com.sun.java.swing.plaf.windows.WindowsBorders.DashedBorder;

/**
 * Created by BaiYunfei on 2017/6/9.
 */
public class User extends Model<User>{

    private static final long serialVersionUID = 1L;

    public static final User dao = new User();

    /**
     * 登陆
     * @return
     */
    public User login(){
        User u = getByUsername(getUsername());
        if(u!= null && u.getPassword().equals(this.getPassword())){
            return u;
        }
        return null;
    }
    
    public Long generateId(){
    	Record record = Db.findFirst("SELECT Max(ID) as id FROM [User]");
    	return record.getLong("id") + 1;
    }

    public User getByUsername(String username){
        return findFirst("SELECT * FROM [User] WHERE Username=?", username);
    }

    public Long getId() {
        return getLong("ID");
    }

    public void setId(Long id) {
        set("ID",id);
    }

    public String getUsername() {
        return getStr("Username");
    }

    public void setUsername(String username) {
        set("Username", username);
    }

    public String getPassword() {
        return getStr("Password");
    }

    public void setPassword(String password) {
        set("Password", password);
    }

    public Integer getRole() {
        return getInt("Role");
    }

    public void setRole(Integer role) {
        set("Role",role);
    }
    
    public User create(String username){
    	Long id = generateId();
    	int success = Db.update("INSERT INTO [User]([ID],[Username],[Password]) VALUES(?,?,?)",generateId(),username,username);
    	if(success >= 0){
    		return findById(id);
    	}
    	return null;
    }

}
